<?php

namespace app\client\controller;

use app\common\controller\Frontend;
use app\common\enums\AccountTypeEnum;
use app\common\enums\ClassHourTypeEnum;
use app\common\enums\LearnMeansEnum;
use app\common\model\banxi\core\CoreAccountClassHour;
use app\common\model\banxi\Grade;
use app\common\model\banxi\learn\LearnSayQuestionAnswerRecord;
use app\common\model\banxi\learn\LearnSayQuestionRecord;
use app\common\model\banxi\learn\LearnSkRecord;
use think\exception\ValidateException;
use think\facade\Validate;

class User extends Frontend
{
    protected array $noNeedLogin = [''];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 获取用户信息
     * @return void
     */
    public function userInfo()
    {
        $userInfo = $this->auth->getUserInfo();

        //统计信息
        $CoreAccountClassHourModel = new CoreAccountClassHour();
        $userAccountClass = $CoreAccountClassHourModel->where(['studentId' => $userInfo['id'], 'accountType' => AccountTypeEnum::STUDENT])
            ->field('class30Minute,class60Minute,class30MinuteTotal,class60MinuteTotal,class30MinuteFreeze,class60MinuteFreeze')
            ->find();

        //30分钟课程次数
        $C_30_remain_num = $CoreAccountClassHourModel->classMinutes(ClassHourTypeEnum::C_30, $userAccountClass);//30分钟课程剩余次数
        $C_30_remain_freeze_num = $CoreAccountClassHourModel->classMinutesFreeze(ClassHourTypeEnum::C_30, $userAccountClass);//30分钟课程冻结次数
        //60分钟课程次数
        $C_60_remain_num = $CoreAccountClassHourModel->classMinutes(ClassHourTypeEnum::C_60, $userAccountClass);//60分钟课程剩余次数
        $C_60_remain_freeze_num = $CoreAccountClassHourModel->classMinutesFreeze(ClassHourTypeEnum::C_60, $userAccountClass);//60分钟课程冻结次数
        //剩余课时
        $totalRemaining = bcadd((string)$C_30_remain_num, (string)$C_60_remain_num, 0);
        $totalFrozen = bcadd((string)$C_30_remain_freeze_num, (string)$C_60_remain_freeze_num, 0);
        $remainingClass = bcsub($totalRemaining, $totalFrozen, 0);
        //上课次数
        $learnSkRecord = new LearnSkRecord();
        $classesCount = $learnSkRecord->where([
            'studentId' => $userInfo['id'],
            'isEnd' => 1
        ])->count();
        //掌握句子
        $learnSayQuestionAnswerRecordModel = new LearnSayQuestionAnswerRecord();
        $masterSentences = $learnSayQuestionAnswerRecordModel->alias('a')
            ->join('ba_banxi_learn_say_question_record b', 'a.recordId = b.id')
            ->where('a.isCorrect', 1)
            ->where('a.del', 0)  // 添加此条件
            ->where('b.learnMeans', LearnMeansEnum::E1)
            ->where('b.studentId', $userInfo['id'])
            ->where('b.isSubmit', 1)
            ->where('b.del', 0)
            ->count();
        //自学上课时长
        $learnSayQuestionRecordModel = new LearnSayQuestionRecord();
        $answerDurationTotal = $learnSayQuestionRecordModel->where([
            'learnMeans' => LearnMeansEnum::E2,
            'studentId' => $userInfo['id'],
            'isSubmit' => 1
        ])->sum('answerDuration');

        $statistics = [
            "classesCount" => (int)$classesCount,
            "answerDurationTotal" => (int)$answerDurationTotal,
            "masterSentences" => (int)$masterSentences,
            "remainingClass" => (int)$remainingClass
        ];
        $userInfo['statistics'] = $statistics;
        $this->ok(__('Operation completed'), $userInfo);
    }

    public function updateInfo()
    {
        $param = $this->request->param([
            'avatar' => '',
            'name' => '',
            'gradeId' => '',
            'sex' => '',
        ]);
        try {
            $validate = Validate::rule([
                'gradeId' => function ($value) {
                    if (!$value) {
                        return true;
                    }
                    $gradeInfo = Grade::where('id', $value)->find();
                    if (!$gradeInfo) {
                        return '年级不存在';
                    }
                    return true;
                },
                'sex' => function ($value) {
                    if (!$value) {
                        return true;
                    }
                    if (!in_array($value, [1, 2])) {
                        return '请设置正确的性别';
                    }
                    return true;

                },
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $user = $this->auth->getUser();
        if ($param['avatar']) {
            $user->avatar = $param['avatar'];
        }
        if ($param['name']) {
            $user->name = $param['name'];
        }
        if ($param['gradeId']) {
            $user->gradeId = $param['gradeId'];
        }
        if ($param['sex']) {
            $user->sex = $param['sex'];
        }
        $user->save();
        $this->ok(__('Operation completed'));
    }


}